package com.opensso.sdk.client;

/**
 * 访问sso的客户端
 * Created by lixin on 2018/8/6.
 */
public enum SSOClient {
    Instance,;

    private String apikey;//验证授权
    private String token;//登录的token
    private String host;//请求主机
//    private String callBackUrl;//回调地址

    /**
     * 配置基本信息
     *
     * @param apikey 用于验证授权
     * @return SSOClient
     */
    public SSOClient apikey(String apikey) {
        this.apikey = apikey;
        return this;
    }

    /**
     * 请求 sso的url设置
     *
     * @param host 主机 [IP,域名,http://IP,http://domain,https://IP,https://domain]
     * @return SSOClient
     */
    public SSOClient host(String host) {
        this.host = host;
        return this;
    }

//    /**
//     * 设置回调地址
//     *
//     * @param callBackUrl 回调地址 如：http://ip:port/login/invalidate
//     * @return SSOClient
//     */
//    public SSOClient invalidateCallBackUrl(String callBackUrl) {
//        this.callBackUrl = Base64.encodeBase64URLSafeString(callBackUrl.getBytes());
//        return this;
//    }

    /**
     * 设置登录的token
     *
     * @param token 登录的token
     * @return SSOClient
     */
    public SSOClient token(String token) {
        this.token = token;
        return this;
    }

    /**
     * 验证登陆token是否有效
     *
     * @return true/false
     */
    public boolean verifyToken() {
        SSORequest ssoRequest = new SSORequest();
        String api = UrlEnum.genUrl(this.host, UrlEnum.Verify_Token_Url);
        SSOResponse ssoResponse = ssoRequest.authorizationPost(api, token, apikey);
        return ssoResponse.isSuccess();
    }

    /**
     * 刷新token
     *
     * @param apikey apikey
     * @return token
     */
    public String refreshToken(String apikey) {
        SSORequest ssoRequest = new SSORequest();
        String api = UrlEnum.genUrl(this.host, UrlEnum.RefreshToken_Url);
        SSOResponse ssoResponse = ssoRequest.refreshPost(api, token, apikey);
        if (ssoResponse.isSuccess()) {
            return ssoResponse.getData().toString();
        } else {
            return null;
        }
    }

    /**
     * 刷新 token时间
     *
     * @return token
     */
    public String refreshTokenTimeout() {
        SSORequest ssoRequest = new SSORequest();
        String api = UrlEnum.genUrl(this.host, UrlEnum.RefreshToken_Timeout_Url);
        SSOResponse ssoResponse = ssoRequest.authorizationPost(api, token, apikey);
        if (ssoResponse.isSuccess()) {
            return ssoResponse.getData().toString();
        } else {
            return null;
        }
    }


    /**
     * 注销登录
     *
     * @return true/false
     */
    public boolean invalidate() {
        SSORequest ssoRequest = new SSORequest();
        String api = UrlEnum.genUrl(this.host, UrlEnum.Invalidate_Url);
        SSOResponse ssoResponse = ssoRequest.authorizationPost(api, token, apikey);
        return ssoResponse.isSuccess();
    }
}
